package com.study.leetcode;

public class Solution_36 {
    public static boolean isValidSudoku(char[][] board) {
        boolean isValid;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == '.') {
                    continue;
                }
                isValid = onlyAppearOnceInCols(board, i, j)
                        && onlyAppearOnceInRows(board, i, j)
                        && onlyAppearOnceInPalaceGrid(board, i, j);
                if (!isValid) {
                    return false;
                }
            }
        }
        return true;
    }

    private static boolean onlyAppearOnceInRows(char[][] board, int row, int col) {
        for (int j = 0; j < board.length; j++) {
            if (j != col && board[row][j] == board[row][col]) {
                return false;
            }
        }
        return true;
    }

    private static boolean onlyAppearOnceInCols(char[][] board, int row, int col) {
        for (int j = 0; j < board.length; j++) {
            if (j != row && board[j][col] == board[row][col]) {
                return false;
            }
        }
        return true;
    }

    private static boolean onlyAppearOnceInPalaceGrid(char[][] board, int row, int col) {
        int indexGridRow = row / 3;
        int indexGridCol = col / 3;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (i != row
                        && j != col
                        && board[i + indexGridRow * 3][indexGridCol * 3 + j] == board[row][col]
                ) {
                    return false;
                }
            }
        }
        return true;

    }


    public static void main(String[] args) {
        char[][] sudokuMap = {
                {'5', '3', '.', '.', '7', '.', '.', '.', '.'},
                {'6', '.', '.', '1', '9', '5', '.', '.', '.'},
                {'.', '9', '8', '.', '.', '.', '.', '6', '.'},
                {'8', '.', '.', '.', '6', '.', '.', '.', '3'},
                {'4', '.', '.', '8', '.', '3', '.', '.', '1'},
                {'7', '.', '.', '.', '2', '.', '.', '.', '6'},
                {'.', '6', '.', '.', '.', '.', '2', '8', '.'},
                {'.', '.', '.', '4', '1', '9', '.', '.', '5'},
                {'.', '.', '.', '.', '8', '.', '.', '7', '9'}
        };
        boolean validSudoku = isValidSudoku(sudokuMap);
        System.out.println("validSudoku = " + validSudoku);
    }

}

